<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      height: 3000px;
    }

    .floor {
      width: 500px;
      height: 300px;
      border: 1px solid #000;
    }

    a {
      text-decoration: none;
      color: #000;
    }

    .sidebar {
      position: fixed;
      right: 20px;
      bottom: 200px;
    }

    .sidebar_item div {
      width: 100px;
      height: 50px;
      background-color: #ddd;
      border: 1px solid #666;
      text-align: center;
      line-height: 50px;
    }
  </style>
</head>

<body>
  <div>
    <h2>楼层1</h2>
    <div class="floor"></div>
  </div>

  <div>
    <h2>楼层2</h2>
    <div class="floor"></div>
  </div>

  <div>
    <h2>楼层3</h2>
    <div class="floor"></div>
  </div>

  <div>
    <h2>楼层4</h2>
    <div class="floor"></div>
  </div>

  <div class="sidebar">
    <a href="javascript:void(0)" class="sidebar_item">
      <div>楼层1</div>
    </a>
    <a href="javascript:void(0)" class="sidebar_item">
      <div>楼层2</div>
    </a>
    <a href="javascript:void(0)" class="sidebar_item">
      <div>楼层3</div>
    </a>
    <a href="javascript:void(0)" class="sidebar_item">
      <div>楼层4</div>
    </a>
  </div>

  <script>
    // 获取元素
    let items = document.querySelectorAll(".sidebar_item");
    let floors = document.querySelectorAll("h2");
    let timerId = null;
    // 注册滚动事件
    items.forEach(function (item, i) {
      item.addEventListener("click", function () {
        clearInterval(timerId);
        // console.log(1);
        // 当前滚动距离
        let current = document.documentElement.scrollTop;
        // 目标滚动距离
        let target = floors[i].offsetTop;
        //定时器  向下滚动
        if (target > current) {
          timerId = setInterval(function () {
            current += 20;  // 增加滚动距离
            document.documentElement.scrollTop = current;
            if (Math.abs(target - current) <= 20) {  // 当目标滚动距离和当前滚动距离的绝对值小于20
              clearInterval(timerId);               // 清除浮动
              timerId = null;
              document.documentElement.scrollTop = target;  // 目标滚动距离赋值给当前滚动距离
            }
          }, 5)
        } else {
          // 向上滚动
          timerId = setInterval(function () {
            current -= 20;  // 减少滚动距离
            document.documentElement.scrollTop = current;
            if (Math.abs(target - current) <= 20) {
              clearInterval(timerId);
              timerId = null;
              document.documentElement.scrollTop = target;
            }
          }, 5)
        }
      })
    })

  </script>
</body>

</html>